package com.ld.oauth2.config.oauth.handle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;

/**
 * 当同一个用户的session达到数量时 执行这个类
 */
public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    @Autowired
    CustomAuhtenticationFailureHandler customAuhtenticationFailureHandler;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        UserDetails principal = (UserDetails)event.getSessionInformation().getPrincipal();
        AuthenticationException authenticationException = new AuthenticationServiceException(String.format("已经有一个用户[%s]在另外一个地方上线，你被迫下线",principal.getUsername()));
        event.getRequest().setAttribute("toAuthentication",true);
        customAuhtenticationFailureHandler.onAuthenticationFailure(event.getRequest(),event.getResponse(),authenticationException);
    }
}
